<?php

namespace app\admin\controller\coupon;

use app\common\controller\Backend;
use app\common\model\Coupon;
use \app\common\model\CouponSetting as CouponSettingModel;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

class Couponsetting extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,name,title';

    /**
     * @var $model \app\common\model\CouponSetting
     */
    protected $model;

    public function _initialize()
    {
        $this->model = model('CouponSetting');
        $this->loadTablelang();
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        $this->assign('statusMap' , CouponSettingModel::$statusMap);
        $this->assign('typeMap' , CouponSettingModel::$typeMap);
        $this->assign('ruleMap' , CouponSettingModel::$ruleMap);
        $this->assign('dateTypeMap' , CouponSettingModel::$dateTypeMap);

    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order('id desc')
                ->paginate($limit)->each(function ($item, $key) {
                    $item['get_nums'] = Coupon::where('setting_id',$item['id'])->count();
                    return $item;
                });
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }



    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params['rule'] != $row['rule']){
                    $this->error('类型不可改变');
                }
                $result = false;
                Db::startTrans();
                try {
                    $result = \app\common\model\CouponSetting::update($params,['id'=>$ids]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return parent::edit($ids);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (in_array($params['rule'], [CouponSettingModel::RULE_BIRTHDAY, CouponSettingModel::RULE_NEW])) {
                    if ($this->model->checkRuleCount($params['rule'])) {
                        $this->error('该类型优惠券已存在');
                    }
                }
                $result = false;
                Db::startTrans();
                try {
                    $result = \app\common\model\CouponSetting::create($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

}